package com.sz.biz.app.web.security;

import com.sz.common.core.service.Principal;
import com.sz.common.core.service.PrincipalUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public abstract class AbstractUserRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        //仅支持UsernamePasswordToken类型的Token
        return token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        List<String> userRoles = new ArrayList<>();
        List<String> userPermissions = new ArrayList<>();
        Principal principal = PrincipalUtils.tryToGetPrincipal();
        if (principal != null) {
            userRoles.addAll(principal.getRoles());
            userPermissions.addAll(principal.getPermissions());
        }
        //为当前用户设置角色和权限
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(userRoles);
        authorizationInfo.addStringPermissions(userPermissions);
        return authorizationInfo;
    }

    @Override
    protected boolean isPermitted(Permission permission, AuthorizationInfo info) {
        Principal principal = PrincipalUtils.tryToGetPrincipal();
        if (principal == null || principal.isAnonymous()) {
            return false;
        }
        if (principal.isRoot() || principal.isAdmin()) {
            return true;
        }
        return super.isPermitted(permission, info);
    }
}

